package com.lincoln.framework.tag;

import com.lincoln.framework.hibernate.Page;
import com.lincoln.framework.utils.ParameterChecker;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;

/**
 * 参与排序逻辑处理类
 *
 * @author		jared
 * 
 */
public class SortColumnTag  extends TagSupport{
	
	/**
	 *	排序列数据库字段
	 */
	private String sortAttr;
	
	/**
	 * 列名称
	 */
	private String columnName;

	/**
	 * 表名
	 */
	private String targetForm;
	
	private Page pageObj;
	
	public int doStartTag() throws JspException { 
        JspWriter out = pageContext.getOut();
        try{
        	//判断结果集信息
			StringBuilder sb = new StringBuilder();
			String alinkName = "column_"+targetForm.trim()+"_"+sortAttr.replace(".", "_");
			if (pageObj.getResult() != null && pageObj.getResult().size() > 0) {
				if (isOrderByCurrentColumn(pageObj)) {
					if (pageObj.getOrder().equals(Page.ASC)) {
						sb.append("<a id=" + alinkName + " href=\"javascript:sortcolumn('" + targetForm.trim() + "','" + sortAttr + "')\" class=\"text-primary\">" + columnName + "&nbsp;<i class=\"fa fa-caret-down\"></i></a>");
					} else {
						sb.append("<a id=" + alinkName + "  href=\"javascript:sortcolumn('" + targetForm.trim() + "','" + sortAttr + "')\" class=\"text-primary\">" + columnName + "&nbsp;<i class=\"fa fa-caret-up\"></i></a>");
					}
				}else{
					sb.append("<a id=" + alinkName + " href=\"javascript:sortcolumn('" + targetForm.trim() + "','" + sortAttr + "')\" class=\"text-primary\">" + columnName + "&nbsp;<i class=\"fa fa-sort\"></i></a>");
				}
			} else {
				sb.append(columnName);
			}
        	out.print(sb);
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return super.doStartTag();  
  
	}
	
	//判断当前form查询是否按照当前列进行排序
	private boolean isOrderByCurrentColumn(Page pageObj){
		return !ParameterChecker.isNullOrEmpty(pageObj.getOrderBy()) && pageObj.getOrderBy().equals(sortAttr);
	}

	public String getSortAttr() {
		return sortAttr;
	}

	public void setSortAttr(String sortAttr) {
		this.sortAttr = sortAttr;
	}

	public String getColumnName() {
		return columnName;
	}

	public void setColumnName(String columnName) {
		this.columnName = columnName;
	}

	public String getTargetForm() {
		return targetForm;
	}

	public void setTargetForm(String targetForm) {
		this.targetForm = targetForm;
	}

	public Page getPageObj() {
		return pageObj;
	}

	public void setPageObj(Page pageObj) {
		this.pageObj = pageObj;
	}
	
}
